package cn.picclife.mwx.manager.sys.task;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.picclife.mwx.manager.sys.mapper.ArchiveMapper;
import cn.picclife.mwx.manager.sys.mapper.DataCollectMapper;
import cn.picclife.mwx.manager.sys.model.bo.ScreenShotBo;
import cn.picclife.mwx.manager.sys.model.po.DataCollect;
import cn.picclife.mwx.manager.sys.model.po.ScreenShot;
import cn.picclife.mwx.manager.util.DateUtil;
import cn.picclife.mwx.manager.util.DateUtil.DateType;
import cn.picclife.mwx.manager.util.ZipUtil;

@Component
public class ArchiveTask {
	
	private static Log log = LogFactory.getLog(ArchiveTask.class);
	
	@Autowired
	private ArchiveMapper mapper;
	@Autowired
	private DataCollectMapper dataMapper;
	//压缩到新路径
	//private String fileDir ="C:/u01";
	private static final int  BUFFER_SIZE = 2 * 1024;
	
	//@Scheduled(cron = "0 0/10 * * * ?") // 每天1点触发  
    public void archive() {
		log.info("----归档管理定时任务开始执行-----");
		//查找归档路径
		String fileDir = mapper.queryAllData().get(0).getArchiveDir()+"/";
		
		//数据归档周期
		String time = mapper.queryAllData().get(0).getEndArchiveTime();
		Date data = DateUtil.addDate(new Date(), DateType.DAY, -Integer.valueOf(time));
		log.info("===date=="+data);
		
		//查找未归档数据(txt)
		List<DataCollect> list = mapper.queryTaskList(data);	
		
		
		ScreenShotBo shotBo = new ScreenShotBo();
		for(DataCollect collect :list) {
			//查找图片
			shotBo.setCollectId(collect.getId());
			List<ScreenShot> shotList = mapper.queryTaskShot(shotBo);
			
			//String source = "C:/u01:/"+collect.getUploadUrl();
			String source = collect.getUploadUrl();
			String url= "";
			for(ScreenShot s : shotList) {				
		        try {
//		        	String shortSource ="D:"+s.getCutDir();
		        	//文件路径
		        	String shortSource =s.getCutDir();
		        	//上传后的文件
					String target =fileDir+collect.getUploadUrl();
					//target = target.substring(0,target.lastIndexOf("/"))+shortSource.substring(shortSource.lastIndexOf("/"),shortSource.lastIndexOf("."))+".zip";
					File zipFile = new File(target.substring(0, target.lastIndexOf("/")));
					if (!zipFile.exists()) {
			    		zipFile.mkdirs();
			    	} 
					//复制文件到指定位置
					if(null==shortSource || !uploadFile(shortSource, target)) {
						continue;
					}
					//压缩文件
					//ZipUtil.ZipCompress(shortSource,target);
					//解压文件
					//String utarget=target.substring(0,target.lastIndexOf("/"));
			        //ZipUtil.zipUncompress(target,utarget);
			        //String UploadUrl = s.getCutDir();
					//String archiveUrl = utarget+UploadUrl.substring(UploadUrl.lastIndexOf("/"),UploadUrl.length());
					s.setCollectId(collect.getId());
					s.setArchiveFlag("1");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
					Date date = new Date();
					String nowDateStr = sdf.format(date);
					s.setArchiveTime(nowDateStr);
					s.setArchiveUrl(target);
					int ret = mapper.updateTaskShot(s);
					if(ret==1) {
						File file = new File(shortSource);
						file.delete();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					log.error("异常信息"+e.getMessage(),e);
				}	
			}		
			try {
				//上传后的文件
				String uploadUrl = collect.getUploadUrl();
				url = fileDir+collect.getUploadUrl();
				//url = url.substring(0,url.lastIndexOf("/"))+url.substring(url.lastIndexOf("/"),url.lastIndexOf("."))+".zip";
				File zipFile = new File(url.substring(0, url.lastIndexOf("/")));
				if (!zipFile.exists()) {
		    		zipFile.mkdirs();
		    	}  
				//压缩文件
		        //ZipUtil.ZipCompress(source,url);	
		        //解压文件
		        //String utarget=url.substring(0,url.lastIndexOf("/"));
		        //ZipUtil.zipUncompress(url,utarget);
				//复制文件到指定位置
		        if(null==uploadUrl || !uploadFile(uploadUrl, url)) {
		        	continue;
		        }
		        collect.setUploadTime(data);
				collect.setArchiveFlag("1");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				Date date = new Date();
				String nowDateStr = sdf.format(date);
				collect.setArchiveTime(nowDateStr);
				//String archiveUrl = utarget+UploadUrl.substring(UploadUrl.lastIndexOf("/"),UploadUrl.length());
				collect.setArchiveUrl(url);
				int ret = mapper.updateTask(collect);
				if(ret == 1) {
					File file = new File(uploadUrl);
					file.delete();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("异常信息"+e.getMessage(),e);
			}	
		}
		
//		try {	
//			fileDir ="D:/root/u01/data/video/";
//			Random rand=new Random();
//			Integer num = rand.nextInt(3) +1;
//			fileDir=fileDir+num.toString()+"/test.zip";
//			 File zipFile = new File(fileDir.substring(0, fileDir.lastIndexOf("/"))); 
//			
//			 if (!zipFile.exists()) {
//	    		 zipFile.mkdirs();
//	    	 }  
//	         ZipUtil.ZipCompress(dir, fileDir);		
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}	
		
		
		//在目录下找到路径并压缩在新路径下
//		try {		
//			 File zipFile = new File(fileDir.substring(0, fileDir.lastIndexOf("/")));
//			 if (!zipFile.exists()) {
//	    		 zipFile.mkdirs();
//	    	 }  
//	         ZipUtil.ZipCompress(dir, fileDir);		
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}	
//		//删除原来目录下的文件
//		ZipUtil.deleteFile(dir);
//		//修改collect中的数据
//		for(DataCollect collect :list) {
//			collect.setUploadTime(data);
//			collect.setArchiveFlag("1");
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//			Date date = new Date();
//			String nowDateStr = sdf.format(date);
//			collect.setArchiveTime(nowDateStr);
//			collect.setArchiveUrl(fileDir);
//			mapper.updateTask(collect);
//		}
        log.info("----归档管理定时任务执行结束-----");
    }
	
	/**
	 * 将文件拷贝到指定目录
	 * @param inputFile
	 * @param outputPath
	 */
	private boolean uploadFile(String inputFile, String outputPath) {
		boolean flag = false;
		File file = new File(inputFile);
		File uploadFile = new File(outputPath);
		//如果文件存在，将文件上传到指定文件下
		if(file.isFile()) {
			FileInputStream fos;
			BufferedInputStream bis;
			FileOutputStream out;
			BufferedOutputStream bos;
			try {
				out = new FileOutputStream(uploadFile);
				bos = new BufferedOutputStream(out);
				fos = new FileInputStream(file);
				bis = new BufferedInputStream(fos);
				int len = -1;
				//将源文件写入到指定文件下
				byte[] buf = new byte[1024];
				while((len = bis.read(buf))!=-1) {
					bos.write(buf,0,len);
					bos.flush();
				}
				bos.close();
				out.close();
				bis.close();
				fos.close();
				return true;
			}catch (Exception e) {
				log.error(file.getName()+"文件上传失败："+e);
				return flag;
			}
		}else {
			log.info(file.getName()+"文件不存在");
			return flag;
		}
	}
	
}
